<template>
  <view class="container">
    <!-- 背景图 -->
    <image
        src="@/static/beijing.jpg"
        class="blur-image"
        mode="aspectFill"
    ></image>

    <!-- 颜色遮罩层 -->
    <view class="color-overlay"></view>

    <!-- 头部区域 -->
    <UniMusicHead
        class="music-head"
        :title="currentSong.name"
        :showBack="true"
        @back="goBack"
    ></UniMusicHead>

    <!-- 歌曲封面和基本信息 -->
    <view class="song-info">
      <!-- 旋转唱片效果 -->
      <view class="disc-container">
		<image
			src="/static/needle.png"
      class="needle"
		></image>
        <image
            :src="currentSong.al ? currentSong.al.picUrl : defaultCover"
            class="cover-img"
            :class="{ 'disc-rotate': isPlaying }"
        ></image>

        <image
            src="@/static/disc.png"
            class="disc"
            :class="{ 'disc-rotate': isPlaying }"
        ></image>
      </view>

      <view class="song-meta">

        <text class="song-title">{{ currentSong.name }}</text>

        <!--歌词-->
        <view class="lyrics">
          <view v-for="(line, index) in displayedLyrics" :key="index" class="lyric-line">
            <text :class="{ active: line.isActive }">{{ line.text }}</text>
          </view>
        </view>

        <view class="progress-container">
          <text class="time-text">{{ formatTime(currentProgress) }}</text>
          <slider
              class="progress-slider"
              :value="currentProgress"
              :max="duration"
              @change="seekTo"
              activeColor="#FF005C"
              backgroundColor="#e0e0e0"
              block-size="16"
          />

        </view>



        <!-- 播放控制 -->
        <view class="controls">
          <image src="/static/shangyishou.png" @tap="prevSong" class="shangyishou"></image>
          <image
              class="control-btn"
              :class="{ 'icon-pause': isPlaying, 'icon-play': !isPlaying }"
              @tap="togglePlay"
          ></image>
          <image src="/static/xiayishou.png" @tap="nextSong" class="xiayishou"></image>
        </view>
      </view>
    </view>
  </view>
</template>


<script>
import UniMusicHead from "../../components/UniMusicHead/UniMusicHead.vue";
import { getPlaylistDetail } from '@/common/api.js';

export default {
  components: { UniMusicHead },
  data() {
    return {
      currentLyric: '正在加载歌词...',
      playlistId: null,
      currentSongIndex: 0,
      currentProgress: 0,
      duration: 180,
      progressInterval: null,
      playlist: [],
      audioContext: null,
      currentSong: {},
      isFollowed: false,
      isPlaying: false,
      defaultCover: 'https://p1.music.126.net/XXuW5hT5Zc4oUOYNkBZ5DA==/18686210686447752.jpg',
      lyrics: [], // 新增歌词数组
      currentLyricIndex: 0 // 当前歌词索引
    };
  },
  computed: {
    displayedLyrics() {
      if (!this.lyrics.length) {
        return [{ text: '正在加载歌词...', isActive: false }];
      }

      const lines = [];
      const currentIndex = this.currentLyricIndex;

      // 上一句
      if (currentIndex - 1 >= 0) {
        lines.push({ text: this.lyrics[currentIndex - 1].lyric, isActive: false });
      }

      // 当前句
      if (this.lyrics[currentIndex]) {
        lines.push({ text: this.lyrics[currentIndex].lyric, isActive: true });
      }

      // 下一句
      if (currentIndex + 1 < this.lyrics.length) {
        lines.push({ text: this.lyrics[currentIndex + 1].lyric, isActive: false });
      }

      return lines;
    },
    artistNames() {
      if (!this.currentSong.ar || !Array.isArray(this.currentSong.ar)) {
        return '未知歌手';
      }
      return this.currentSong.ar.map(artist => artist.name).join('/');
    }
  },
  onLoad(options) {
    if (options.id && options.index !== undefined) {
      this.currentSongIndex = parseInt(options.index);
      this.getPlaylistDetail(options.id)
          .then(() => this.initCurrentSong());
    }
  },

  methods: {
    parseLyrics(lyricString) {
      const lines = lyricString.split('\n');
      const pattern = /\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)/;
      const parsed = [];

      lines.forEach(line => {
        const matches = line.match(pattern);
        if (matches) {
          const minutes = parseInt(matches[1], 10);
          const seconds = parseInt(matches[2], 10);
          const milliseconds = parseInt(matches[3], 10);
          const time = minutes * 60 + seconds + milliseconds / 1000;
          const text = matches[4].trim();

          parsed.push({time, lyric: text});
        }
      });

      return parsed;
    },
    async loadLyrics(songId) {
      try {
        const response = await uni.request({
          url: `https://music.163.com/api/song/lyric?id=${songId}&lv=1&tv=-1`,
          success: (res) => {
            if (res.statusCode === 200 && res.data.lrc) {
              this.lyrics = this.parseLyrics(res.data.lrc.lyric);
            } else {
              this.lyrics = [{ time: 0, lyric: '暂无歌词' }];
            }
          },
          fail: () => {
            this.lyrics = [{ time: 0, lyric: '加载歌词失败' }];
          }
        });
      } catch (e) {
        this.lyrics = [{ time: 0, lyric: '加载歌词失败' }];
      }
    },
    async getPlaylistDetail(id) {
      try {
        const playlist = await getPlaylistDetail(id);
        this.playlistId = id;
        this.playlist = playlist.tracks || [];
        this.currentSong = this.playlist[this.currentSongIndex] || {};
      } catch (error) {
        uni.showToast({
          title: `加载失败: ${error.message}`,
          icon: 'none',
          duration: 3000
        });
      }
    },
    toggleFollow() {
      this.isFollowed = !this.isFollowed;
      uni.showToast({
        title: this.isFollowed ? '已关注' : '已取消关注',
        icon: 'none'
      });
    },
    formatTime(seconds) {
      const min = Math.floor(seconds / 60);
      const sec = seconds % 60;
      return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
    },

    // 拖动进度条跳转播放位置
    seekTo(e) {
      const seekTime = e.detail.value;
      this.currentProgress = seekTime;

      if (this.audioContext) {
        // 停止当前播放
        this.audioContext.pause();

        // 销毁旧实例
        this.audioContext.stop();
        this.audioContext = null;

        // 创建新实例并从指定时间开始播放
        this.initAudioContext(seekTime);
        this.audioContext.play();
      }
    },

    // 模拟播放进度更新
    startProgressUpdate() {
      if (this.progressInterval) clearInterval(this.progressInterval);

      this.progressInterval = setInterval(() => {
        if (this.isPlaying && this.currentProgress < this.duration) {
          this.currentProgress++;

          // 更新歌词
          this.updateLyricDisplay(this.currentProgress);
        }
      }, 1000);
    },
    updateLyricDisplay(currentTime) {
      for (let i = this.currentLyricIndex; i < this.lyrics.length; i++) {
        if (currentTime < this.lyrics[i].time) {
          if (i > 0) {
            this.currentLyricIndex = i - 1;
            this.highlightLyric(this.currentLyricIndex);
          }
          break;
        }
        this.currentLyricIndex = i;
      }

      if (this.currentLyricIndex === this.lyrics.length - 1) {
        this.highlightLyric(this.currentLyricIndex);
      }
    },

    highlightLyric(index) {
      if (this.lyrics[index]) {
        this.currentLyric = this.lyrics[index].lyric;
      }
      // 这里可以更新页面上的歌词组件状态或 DOM 高亮
    },

    initCurrentSong() {
      if (this.progressInterval) clearInterval(this.progressInterval);

      this.duration = 180; // 模拟总时长
      this.currentLyricIndex = 0;

      this.initAudioContext();
      this.play();
      this.startProgressUpdate();

      // 加载当前歌曲的歌词
      if (this.currentSong.id) {
        this.loadLyrics(this.currentSong.id);
      }
    },

    initAudioContext(seekTime = 0) {
      this.audioContext = uni.createInnerAudioContext();
      this.audioContext.src = `https://music.163.com/song/media/outer/url?id=${this.currentSong.id}.mp3`;

      // 记录初始播放位置
      this.audioContext.startTime = seekTime; // ⬅️ 跳转的关键！

      // 可选事件监听
      this.audioContext.onPlay(() => {
        console.log('音频开始播放');
        this.isPlaying = true;
      });

      this.audioContext.onPause(() => {
        console.log('音频暂停');
        this.isPlaying = false;
      });

      this.audioContext.onStop(() => {
        console.log('音频停止');
        this.isPlaying = false;
      });

      this.audioContext.onError((err) => {
        console.error('音频播放错误', err);
        uni.showToast({ title: '播放失败', icon: 'none' });
      });

      // 监听音频自然结束
      this.audioContext.onEnded(() => {
        this.nextSong(); // 自动下一首
      });
    },
    play() {
      if (this.audioContext) {
        this.audioContext.play();
        this.isPlaying = true;
      }
    },
    pause() {
      if (this.audioContext) {
        this.audioContext.pause();
        this.isPlaying = false;
      }
    },

    togglePlay() {
      if (!this.audioContext) {
        this.initAudioContext();
        this.play();
        return;
      }

      if (this.isPlaying) {
        this.pause();
      } else {
        this.play();
      }
    },
    prevSong() {
      if (this.playlist.length > 0) {
        this.currentSongIndex = (this.currentSongIndex - 1 + this.playlist.length) % this.playlist.length;
        this.resetPlayer();
      }
    },
    nextSong() {
      if (this.playlist.length > 0) {
        this.currentSongIndex = (this.currentSongIndex + 1) % this.playlist.length;
        this.resetPlayer();
      }
    },
    resetPlayer() {
      // 停止当前播放的音频
      if (this.audioContext) {
        this.audioContext.stop(); // 停止播放
        this.audioContext = null; // 销毁旧实例
      }

      // 切换歌曲
      this.currentSong = this.playlist[this.currentSongIndex] || {};
      this.currentProgress = 0;

      // 初始化新歌曲
      this.initCurrentSong();
    },
    goBack() {
      uni.navigateBack();
    },

  }
};
</script>


<style lang="scss">
.container {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}
.needle{
  width: 50%;
  height: 50%;
  margin-left: 120px;
  margin-top: -10px;
  border-radius: 50%;
  z-index: 3;
}
.blur-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  filter: blur(20px) brightness(0.9) saturate(1.5) contrast(1.1);
  transform: scale(1.1);
  z-index: 1;
  opacity: 0.9;

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 60%;
    background: linear-gradient(transparent, #f5f5f5);
  }
}

.color-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 2;
  background: linear-gradient(45deg, rgba(255, 0, 92, 0.5), rgba(68, 0, 255, 0.5));
  mix-blend-mode: color;
  opacity: 0.4;
}

.music-head {
  position: absolute;
  top: 40rpx;
  left: 0;
  right: 0;
  z-index: 10;
  background-color: transparent;
}

.song-info {
  position: relative;
  z-index: 3;
  padding: 10%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 100rpx;
  margin-bottom: 60rpx;
}

.disc-container {
  position: relative;
  width: 500rpx;
  height: 500rpx;
  border-radius: 50%;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
  border: 4rpx solid rgba(255, 255, 255, 0.4);
  margin-bottom: 40rpx;

  .cover-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    z-index: 2;
  }

  .disc {
    position: absolute;
    top: -5%;
    left: -5%;
    width: 110%;
    height: 110%;
    border-radius: 50%;
    transition: transform 0.5s;
    z-index: 2;
  }

  .disc-rotate {
    animation: rotate-disc 5s linear infinite;
  }

  @keyframes rotate-disc {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
}

.song-meta {
  width: 100%;
  text-align: center;
  color: white;
  margin-top: 30rpx;
}

.song-title {
  font-size: 40rpx;
  font-weight: bold;
  line-height: 1.5;
  
  margin-bottom: 20rpx;
  display: block;
}

.artist-name {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  display: block;
  
  margin-bottom: 60rpx;
}

.controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40rpx;
}

.control-btn {
  width: 120rpx; /* 图标宽度 */
  height: 120rpx; /* 图标高度 */
  display: inline-block;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}
/* 暂停状态下的图标样式 */
.icon-pause {
  background-image: url("@/static/zanting.png"); /* 暂停图标路径 */
  width: 120rpx;
  height: 120rpx;
}

/* 播放状态下的图标样式 */
.icon-play {
  background-image: url('@/static/bofan.png'); /* 播放图标路径 */
  width: 121rpx;
  height: 121rpx;
}

.shangyishou{
  width: 100rpx;
  height: 100rpx;
  margin-right: 5%;
}
.xiayishou{
  width:100rpx;
  height: 100rpx;
  margin-left: 5%;
}
.cover-img {
  position: absolute;
  top: 19%;
  left: 17%;
  width: 65%; /* 比 disc 小一圈 */
  height: 65%;
  border-radius: 50%;
  z-index: 1;
  background-color: #fff; /* 可选背景色，防止透明问题 */
}
.progress-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 90%;
  margin: 0 auto;
  margin-bottom: 5%;
}

.progress-slider {
  flex: 1;
  margin: 0 20rpx;
}

.time-text {
  font-size: 30rpx;
  color: rgba(255, 255, 255, 0.7);
}
.follow-button {
  position: absolute;
  margin-left: 13px;
  bottom: 180px;
  padding: 8rpx 20rpx;
  background-color: rgba(255, 255, 255, 0.7); // 半透明白底
  color: #333;

  font-size: 26rpx;
  border-radius: 40rpx;
  z-index: 10;


  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
  transition: background-color 0.3s;

  &:active {
    background-color: rgba(255, 255, 255, 0.9);
  }
}
.lyrics {
  height: 150rpx; /* 高度适配三行 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 40rpx;
}

.lyric-line {
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
  width: 100%;
}

.lyric-line .active {
  color: #FF005C !important;
  font-weight: bold;
}
</style>